﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.ViewModels;
using Windows.UI.Popups;
using Saisie_des_prélèvements.Common;
using System.Globalization;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class ClientsPage : Saisie_des_prélèvements.Common.LayoutAwarePage
    {
        List<ClientTakenViewModel> list_infos;
        int ClientID;
        public ClientsPage()
        {
            this.InitializeComponent();
           
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            cboZone.ItemsSource = (new ZoneViewModel()).GetZoneSelection();
            cboZone.SelectedIndex = App.ZoneIndex;
            cboZone_SelectionChanged(null, null);
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            
        }

        private void txtZone_GotFocus(object sender, RoutedEventArgs e)
        {
            cboZone.IsDropDownOpen = true;
        }

        private void cboZone_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cboZone.SelectedValue == null) cboZone.SelectedValue = cboZone.Items[0];
            int ZoneId = ((ZoneViewModel)cboZone.SelectedValue).zone_id;
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                list_infos = (new ClientTakenViewModel()).GetClientsByZone(ZoneId);
                foreach (ClientTakenViewModel z in list_infos)
                {
                    string[] s = z.Status.Split(',');
                    if (s.Length == 1)
                    {
                        switch (s[0])
                        {
                            case "1":
                                z.BGColor = "#9bbb59";
                                break;
                            case "3":
                                z.BGColor = "#9bbb59";
                                break;
                            default:
                                z.BGColor = "#ffffff";
                                break;
                        }
                    }
                    else if (s.Length == 2)
                    {
                        if ((s[0] == "1" && s[1] == "3") || (s[0] == "3" && s[1] == "1"))
                            z.BGColor = "#9bbb59";
                    }
                    List<TakenViewModel> takens = (new TakenViewModel()).GetTakenListByClient(z.ClientTakenId);
                    // Check all taken meet condition
                    foreach (TakenViewModel i in takens)
                    {
                        // Set taken status to 99 when meet condition
                        if (!TakenCondition(i)) i.Status = 99;
                    }

                    // Remove all condition that meet condition from list.
                    takens.RemoveAll(t => t.Status == 99);

                    if (takens.Count == 0) z.Status = "99";
                }
                list_infos.RemoveAll(c => c.Status == "99");
                itemListView.ItemsSource = list_infos;
                itemListView.SelectedValuePath = "ClientTakenId";
            }
            App.ZoneIndex = cboZone.SelectedIndex;
        }

        private async void btnSignature_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            ClientID = int.Parse(btn.Tag.ToString());
            var db = new SQLite.SQLiteConnection(App.DBPath);
            k_client_taken info = db.Table<k_client_taken>().Where(c => c.client_taken_id == ClientID).First();
            if (info.signature == null)
                this.Frame.Navigate(typeof(SignaturePage), ClientID);
            else
            {
                // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
                var messageDialog = new MessageDialog(new msg().client_cancelSignature);

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
                messageDialog.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(this.CommandInvokedHandler)));
                messageDialog.Commands.Add(new UICommand(new msg().msgCancel, new UICommandInvokedHandler(this.CommandInvokedHandler)));

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                // Show the message dialog and wait
                await messageDialog.ShowAsync();
            }

            //((Grid)btn.Parent).Background.SetValue(null, Windows.UI.Colors.Red);
            //((ListViewItem)itemListView.SelectedItem).Background.SetValue(null, Windows.UI.Colors.Red);
        }

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private void CommandInvokedHandler(IUICommand command)
        {
            if (command.Label == "OK")
            {
                using (var db = new SQLite.SQLiteConnection(App.DBPath))
                {
                    var client = db.Table<k_client_taken>().Where(k => k.client_taken_id == ClientID).First();
                    client.signature = null;
                    client.signature_label = null;
                    client.user_create = App.CurrentUserId;
                    client.date_create = DateTime.Now;
                    db.Update(client);
                }

                cboZone_SelectionChanged(null, null);
                //list_infos.Where(t => t.ClientTakenId == ClientID).First().Lock = "ms-appx:///Assets/Very-Basic-Unlock-icon.png";
            }

        }

        private void btnInfo_Click(object sender, RoutedEventArgs e)
        {
            // open the Popup if it isn't open already
            if (!LightDismissAnimatedPopup.IsOpen)
            {
                LightDismissAnimatedPopup.IsOpen = true;

                ClientTakenViewModel info = list_infos.Where(c => c.ClientTakenCode == ((Button)sender).Tag.ToString()).First();
                txtClientCode.Text = info.ClientTakenCode;
                txtName.Text = info.ClientTakenLabel;
                txtAddress1.Text = info.Adr1;
                txtAddress2.Text = info.Adr2;
                txtAddress3.Text = info.Adr3;
                txtCodePostal.Text = info.CodePostal;
                txtVille.Text = info.Ville;
                txtPhone1.Text = info.Phone1;
                txtPhone2.Text = info.Phone2;
            }
            
        }

        private void CloseAnimatedPopupClicked(object sender, RoutedEventArgs e)
        {
            // if the Popup is open, then close it
            if (LightDismissAnimatedPopup.IsOpen) { LightDismissAnimatedPopup.IsOpen = false; }
        }

        private void LightDismissAnimatedPopup_Loaded(object sender, RoutedEventArgs e)
        {
           LightDismissAnimatedPopup.HorizontalOffset = (Window.Current.Bounds.Width - ppuBorder.Width) / 2;
           LightDismissAnimatedPopup.VerticalOffset = (Window.Current.Bounds.Height - ppuBorder.Height) / 2;
           
        }

        private void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemListView.SelectedValue == null) return;
            int CurrentClientTaken = int.Parse(itemListView.SelectedValue.ToString());
            var db = new SQLite.SQLiteConnection(App.DBPath);
            k_client_taken info = db.Table<k_client_taken>().Where(c => c.client_taken_id == CurrentClientTaken).First();
            if (info.signature == null)
                this.Frame.Navigate(typeof(ClientTakenPage), CurrentClientTaken);
        }

        private bool TakenCondition(TakenViewModel taken)
        {
            string scode = taken.SurvCode == null ? "" : taken.SurvCode;
            bool _pass = false;
            if (scode != "")
            {
                DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                Calendar cal = dfi.Calendar;
                string weekOfYear = cal.GetWeekOfYear(DateTime.Today, dfi.CalendarWeekRule, dfi.FirstDayOfWeek).ToString();
                string dOw = ((int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek).ToString();
                if (weekOfYear == "53") weekOfYear = "52";
                
                if (taken.TakenYear.Split('-').Contains<string>(weekOfYear))
                    if (taken.TakenMonth.Split('-').Contains<string>(DateTime.Now.Month.ToString()))
                        _pass = taken.TakenDay.Split('-').Contains<string>(dOw);
            }
            return _pass;
        }

        private void GoBack(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(BasicPage));
        }
    }
}
